package org.chen.aao.subscription.controller;

import org.chen.aao.common.exception.BusinessException;
import org.chen.aao.common.response.Result;
import org.chen.aao.common.subscription.dto.*;
import org.chen.aao.subscription.service.SubscriptionService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/subscription")
@RequiredArgsConstructor
public class SubscriptionController {
    
    private final SubscriptionService subscriptionService;
    
    @PostMapping("/validate")
    public Result<ValidationResponse> validatePurchase(@Validated @RequestBody ValidateRequest request,
                                                       HttpServletRequest httpRequest) {
        Long userId = getUserId(httpRequest);
        return Result.success(subscriptionService.validatePurchase(request, userId));
    }
    
    @GetMapping("/status")
    public Result<SubscriptionStatusResponse> getSubscriptionStatus(HttpServletRequest request) {
        Long userId = getUserId(request);
        return Result.success(subscriptionService.getSubscriptionStatus(userId));
    }

    @GetMapping("/status/{id}")
    public Result<SubscriptionStatusResponse> getSubscriptionStatusById(@PathVariable("id") Long userId) {
        return Result.success(subscriptionService.getSubscriptionStatus(userId));
    }
    
    @PostMapping("/cancel")
    public Result<?> cancelSubscription(HttpServletRequest request) {
        Long userId = getUserId(request);
        subscriptionService.cancelSubscription(userId);
        return Result.success("订阅已取消");
    }
    
    @GetMapping("/products")
    public Result<ProductListResponse> getProducts() {
        // 返回可用的订阅产品列表
        return Result.success(ProductListResponse.builder()
                .products(List.of(
                        ProductInfo.builder()
                                .productId("ai_tool_basic_monthly")
                                .name("基础版月度订阅")
                                .price("19.90")
                                .currency("CNY")
                                .period("MONTHLY")
                                .features(List.of(
                                        "每日100次AI聊天",
                                        "每日50次语音转文字",
                                        "每日200次翻译"
                                ))
                                .build(),
                        ProductInfo.builder()
                                .productId("ai_tool_premium_monthly")
                                .name("高级版月度订阅")
                                .price("59.90")
                                .currency("CNY")
                                .period("MONTHLY")
                                .features(List.of(
                                        "每日1000次AI聊天",
                                        "每日500次语音转文字",
                                        "每日2000次翻译",
                                        "GPT-4模型访问"
                                ))
                                .build(),
                        ProductInfo.builder()
                                .productId("ai_tool_premium_yearly")
                                .name("高级版年度订阅")
                                .price("599.00")
                                .currency("CNY")
                                .period("YEARLY")
                                .features(List.of(
                                        "包含所有高级版功能",
                                        "节省2个月费用",
                                        "优先客服支持"
                                ))
                                .build()
                ))
                .build());
    }
    
    private Long getUserId(HttpServletRequest request) {
        String userIdHeader = request.getHeader("X-User-Id");
        if (userIdHeader == null || userIdHeader.trim().isEmpty()) {
            throw new BusinessException("用户未登录");
        }
        try {
            return Long.valueOf(userIdHeader);
        } catch (NumberFormatException e) {
            throw new BusinessException("用户ID格式错误");
        }
    }
}